package IO流.IO流操作.处理流.对象流;

import java.io.*;
import java.util.Date;

/**
 * 对象流
 * <p>
 * 1.写出后读取
 * 2.读取顺序与写出顺序一致
 * 3.不是所有对象都可以系列化，需Serializable接口
 * <p>
 * ObjectInputStream
 * ObjectOutputStream
 */
public class ObjectTestFile {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //序列化数据和对象
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream dos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("C:\\huangzhi\\workspace\\javaStudy\\src\\IO流\\IO流操作\\处理流\\对象流\\obj.txt")));
        //操作数据类型
        dos.writeUTF("编码辛酸泪");
        dos.writeInt(18);
        dos.writeBoolean(false);
        dos.writeChar('a');
        //加入对象
        dos.writeObject("String对象已实现Serializable接口");
        dos.writeObject(new Date());//Date已实现***接口
        dos.flush();
        dos.close();

        //反序列化
        ObjectInputStream ds = new ObjectInputStream(new BufferedInputStream(new FileInputStream("C:\\huangzhi\\workspace\\javaStudy\\src\\IO流\\IO流操作\\处理流\\对象流\\Obj.txt")));
        //顺序与写出一致
        String msg = ds.readUTF();
        int age = ds.readInt();
        boolean bool = ds.readBoolean();
        char a = ds.readChar();

        Object string = ds.readObject();
        Object date = ds.readObject();


        //序列化的手动还原
        if (string instanceof String){
            String str = (String) string;
            System.out.println(str);
        }
        if (date instanceof Date){
            Date d = (Date) date;
            System.out.println(d);
        }
        ds.close();
    }


}
